import pandas as pd

#trade_details = pd.read_csv("E:\\zhijiren log\\20221017 套利实盘复盘\\ctp_main_hn_trade_detail.csv", encoding="GBK")
trade_details = pd.read_csv("E:\\zhijiren log\\20221017 套利实盘复盘\\蝶套详细分析\\butterfly_trade_detail.csv", encoding="GBK")
#rb_detail = trade_details.loc[trade_details["trade_symbol"].str.contains("rb")]
trade_pairs = []
symbol_pos_buff = {}

for n, rows in trade_details.iterrows():
    print(n)
    signal = rows["signal_name"]
    offset = rows["offset"]
    symbol_buff = symbol_pos_buff.setdefault(signal, [])
    if "OPEN" in offset:
        symbol_buff.append(rows)
    else:
        if symbol_buff:
            #trade_pair = trade_pairs.setdefault(signal, [])
            close_volume = rows["new_trade"]
            while close_volume and symbol_buff:
                open_row = symbol_buff.pop()
                trade_volume = min(abs(close_volume), abs(open_row["new_trade"]))
                if "多" in signal:
                    close_volume = min(0, close_volume + trade_volume)
                    open_row["new_trade"] = max(0, open_row["new_trade"] - trade_volume)
                    direction = "多"
                else:
                    close_volume = max(0, close_volume - trade_volume)
                    open_row["new_trade"] = min(0, open_row["new_trade"]) + trade_volume
                    direction = "空"
                pair = {
                        "signal": signal,
                        "open_time": open_row["trade_time"],
                        "open_price": open_row["new_trade_price"],
                        "open_slip": open_row["slip"],
                        "open_limit_diff": open_row["limit_diff"],
                        "open_limit": open_row["limit_price"],
                        "close_time": rows["trade_time"],
                        "close_price": rows["new_trade_price"],
                        "close_slip": rows["slip"],
                        "close_limit_diff": rows["limit_diff"],
                        "close_limit": rows["limit_price"],
                        "direction": direction,
                        "volume": trade_volume,
                        }
                trade_pairs.append(pair)
                if open_row["new_trade"]:
                    symbol_buff.append(open_row)
